<?php
use Phalcon\Mvc\View;

class PageController extends ControllerBase
{
    public $currPluginRoot; //当前插件的根目录
    public $tbl; //页面的数据表
    public $ext = '.volt'; //文件扩展名
    public $max = 100;

    public function initialize()
    {
        parent::initialize();
        $this->currPluginRoot = BASE_PATH . '/_site/' . $this->siteid . '/page/';
        $this->tbl            = $this->currPluginRoot . 'config.json';
    }

    /**
     * 列表
     */
    public function indexAction()
    {
        $this->tag->prependTitle("页面管理 - ");
        $this->assets->addJs("/static/page/js/page.js");
        $this->view->setVars(
            [
                'crumbData' => [
                    [
                        'name' => $this->view->currentSite[$this->siteid]['name'],
                        'url'  => '/' . $this->siteid . '/dir/index',
                    ],
                    [
                        'name' => '页面管理',
                        'url'  => 'javascript:;',
                        'curr' => 1,
                    ],
                ],
            ]
        );
    }

    /**
     * 创建
     */
    public function createAction()
    {
        $tbl = [];
        if (file_exists($this->tbl)) {
            $string = file_get_contents($this->tbl);
            $tbl    = json_decode($string, true);
            if (count($tbl) >= $this->max) {
                $json = ['code' => 6, 'msg' => '已经达到了创建允许的最大值'];
                $this->response->setJsonContent($json);
                return $this->response;
            }
        }
        //获取数据
        $title = $this->request->getPost('title', ['trim', 'string']);
        $path  = ltrim($this->request->getPost('path', ['trim', 'string']), '/');

        if (empty($title) || empty($path)) {
            $json = ['code' => 2, 'msg' => '参数不足'];
        } else {
            //对存储路径进行识别
            $pattern = '/^[0-9A-Za-z\/\-\_]{5,20}$/';
            if (!preg_match($pattern, $path)) {
                $json = ['code' => 3, 'msg' => '存储路径只接受5-20位的字母,数字,下划线,分割线,斜杠任意组合'];
                $this->response->setJsonContent($json);
                return $this->response;
            }

            //如果设定了斜杠，则检查斜杠
            if (strpos($path, '/')) {
                //最多深度为5
                if (count(explode('/', $path)) > 5) {
                    $json = ['code' => 5, 'msg' => '目录创建深度为5级'];
                    $this->response->setJsonContent($json);
                    return $this->response;
                }

                //创建目录
                $dir = substr($path, 0, strrpos($path, '/'));
                $dir = $this->currPluginRoot . $dir;
                if (!is_dir($dir)) {
                    $ret = mkdir($dir, 0777, true);
                    //第三个参数为true即可以创建多极目录
                    if (!$ret) {
                        $json = ['code' => 4, 'msg' => '目录创建失败'];
                        $this->response->setJsonContent($json);
                        return $this->response;
                    }
                }
            }

            $page = $this->currPluginRoot . $path . $this->ext;
            //验证文件是否存在
            if (file_exists($page)) {
                $json = ['code' => 1, 'msg' => '文件已经存在'];
            } else {
                $content = <<<EF
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title> {$title} </title>
</head>

<body>
默认内容，可以删除再编辑。
</body>
</html>
EF;
                file_put_contents($page, $content);
                $tbl[md5($path)] = ['title' => $title, 'path' => $path];
                $string          = json_encode($tbl, JSON_UNESCAPED_UNICODE);
                file_put_contents($this->tbl, $string);
                $json = ['code' => 0, 'msg' => null];
            }
        }

        $this->response->setJsonContent($json);
        return $this->response;
    }

    /**
     * 编辑
     */
    public function editAction()
    {
        $this->tag->setTitle('编辑页面');
        $this->view->setRenderLevel(View::LEVEL_ACTION_VIEW);
        $this->assets->addCss("/codemirror/codemirror.css");
        $this->assets->addCss("/static/page/css/page.css");
        $this->assets->addJs("/codemirror/codemirror.js");
        $this->assets->addJs("/codemirror/xml.js");
        $this->assets->addJs("/codemirror/htmlmixed.js");
        $this->assets->addJs("/static/page/js/page.js");
        $id  = $this->request->getQuery('id', ['trim', 'string']);
        $tbl = json_decode(file_get_contents($this->tbl), true);
        if (!isset($tbl[$id])) {
            $this->dispatcher->forward(array(
                "controller" => "index",
                "action"     => "error",
                "params"     => array('message' => '记录不存在'),
            ));
        }
        $content = file_get_contents($this->currPluginRoot . $tbl[$id]['path'] . '.volt');

        $this->view->title   = $tbl[$id]['title'];
        $this->view->id      = $id;
        $this->view->content = $content;
    }

    /**
     * 编辑保存
     */
    public function saveAction()
    {
        $id      = $this->request->getPost('id');
        $content = $this->request->getPost('content', "trim");
        $tbl     = json_decode(file_get_contents($this->tbl), true);
        $path    = $this->currPluginRoot . $tbl[$id]['path'] . '.volt';
        if (!is_writable($path)) {
            $json = ['code' => 1, 'msg' => '权限不足，禁止访问。'];
        } else {
            $info = file_put_contents($path, $content);
            $json = ['code' => 0, 'msg' => null];
        }

        $this->response->setJsonContent($json);
        return $this->response;
    }

    /**
     * 删除
     */
    public function deleteAction()
    {
        //获取删除的id
        $ids = $this->request->getPost('ids');

        //读取配置文件
        $tbl = json_decode(file_get_contents($this->tbl), true);

        $tmp = []; //存放删除成功的id

        //循环删除文件
        foreach ($ids as $key => $value) {
            $ret = unlink($this->currPluginRoot . $tbl[$value]['path'] . '.volt');
            if ($ret) {
                $tmp[] = $value;
            }
        }

        //循环清理数据表
        if (empty($tmp)) {
            $json = ['code' => 1, 'msg' => '文件不存在或者权限不够，请检查'];
        } else {
            foreach ($tmp as $key => $value) {
                unset($tbl[$value]);
            }

            //将结果写入数据表
            $info = file_put_contents($this->tbl, json_encode($tbl, JSON_UNESCAPED_UNICODE));
            $json = ['code' => 0, 'msg' => '总计删除 ' . count($tmp) . ' 条记录', 'data' => $tmp];
        }

        $this->response->setJsonContent($json);
        return $this->response;
    }

    public function rowsAction()
    {
        $tbl  = ['data' => [], 'count' => 0, 'current' => 0];
        $page = $this->request->getQuery('page', ['trim', 'int']);
        if (file_exists($this->tbl)) {
            $tbl = array_reverse(json_decode(file_get_contents($this->tbl), true));
            foreach ($tbl as $key => &$value) {
                $path                  = $this->currPluginRoot . '/' . $value['path'] . '.volt';
                $value['size']         = Common::calc(filesize($path));
                $value['filemtime']    = filemtime($path);
                $value['friendlytime'] = Common::contextualTime(filemtime($path));
                $value['url']          = '//' . $this->siteid . '.preview.dev.igoji.net/' . $value['path'] . '.html';
            }
            $pagesize = 20;
            $count    = count($tbl); //总条数
            $total    = ceil($count / $pagesize);
            $start    = ($page - 1) * $pagesize; //偏移量，当前页-1乘以每页显示条数
            $tbl      = array_slice($tbl, $start, $pagesize);
            $this->response->setJsonContent(['data' => $tbl, 'total' => $total, 'pagesize' => $pagesize, 'current' => count($tbl)]);
            return $this->response;
        }
        $this->response->setJsonContent($tbl);
        return $this->response;
    }
}
